package com.geekcoding.geekoj.controller;

import cn.hutool.crypto.SecureUtil;
import com.geekcoding.common.dto.ApiResponse;
import com.geekcoding.common.exceptions.GeekRuntimeException;
import com.geekcoding.geekoj.constant.CommonConstants;
import com.geekcoding.geekoj.dto.User;
import com.geekcoding.geekoj.dto.request.LoginReq;
import com.geekcoding.geekoj.nums.Role;
import com.geekcoding.geekoj.repository.UserEntityRepository;
import com.geekcoding.geekoj.utils.JWTUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController()
@RequestMapping("/user")
@RequiredArgsConstructor
public class LoginController {
    private final UserEntityRepository userEntityRepository;

    @PostMapping("login")
    public ApiResponse login(@RequestBody LoginReq req, HttpServletResponse response){
        val userEntity = userEntityRepository.findStuNo(req.getStuNo());
        if(Objects.isNull(userEntity)){
            throw new GeekRuntimeException("用户不存在");
        }
        if (Objects.isNull(userEntity.getRole()) || userEntity.getRole() != Role.STUDENT) {
            throw new GeekRuntimeException("您不是学生，不可以登录");
        }
        val password = SecureUtil.md5(req.getPwd() + userEntity.getSalt());
        if(!password.equals(userEntity.getPassword())){
            throw new GeekRuntimeException("密码不正确");
        }
        String token = JWTUtils.creatJWT(userEntity);
        response.setHeader(CommonConstants.TOKEN, token);
        return ApiResponse.success(User.of(userEntity, token));
    }
}
